// axios 直接请求

export default ({ app, $axios, env, store, redirect }) => {

    $axios.setHeader('Content-Type', 'application/x-www-form-urlencoded', [
        'post', 'put', 'patch'
    ])

    $axios.onRequest(config => {
        // console.log('----------axios onRequest-------------')

        if (env.useProxy && config.baseURL.indexOf('/') === 0) {
            // config.url = config.url.replace(/^\/api/, '/api/v')
            config.url = config.url.replace(/^\/api/, '/api')
        }

        if (config.url[config.url.length - 1] !== '/') {
            config.url += '/'
        }

        if (store.state.token) {
            config.headers.common['Authentication'] = store.state.token
        } else {
            delete config.headers.common['Authentication']
        }

        return config
    })
    
    // 拦截请求特殊处理
    $axios.onResponse(response => {
        return response
    })

    $axios.onError(error => {
        let errMsg = error
        if (error.response && error.response.status) {
            errMsg = error.response.data
        }

        errMsg.status = false

        if (typeof errMsg.code === 'string' || typeof errMsg.code === 'undefined') {
            // console.log('------------------errMsg---------------------')
            // console.log(errMsg.config.url, '\n')

            errMsg = {
                code: 502,
                status: false,
                // msg: error.code || 502,
                msg: '接口请求失败',
                message: '接口请求失败'
            }
        }

        if (app.$raven) {
            app.$raven.captureException(errMsg)
        }

        // console.log(errMsg)

        // process.exit()
        return Promise.reject(errMsg)
    })
}